//
//  UIScrollView+Empty.m
//  ITC_iOS
//
//  Created by iBenz on 2018/9/17.
//  Copyright © 2018年 Benz.L. All rights reserved.
//

#import "UIScrollView+Empty.h"
#import <objc/runtime.h>
#import "ObjcRuntime.h"
#import "UIColor+Create.h"

NSString *const kEmptyKey = @"kEmptyKey";
@implementation UIScrollView(Empty)
@dynamic isEmpty;

- (void)setIsEmpty:(BOOL)isEmpty {
    UIView *label = self.emptyView;
    if (isEmpty) {
        [self addSubview:label];
        [label mas_updateConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            make.width.lessThanOrEqualTo(self).offset(-60);
        }];
    }
    else {
        [label removeFromSuperview];
    }
}

- (UIView *)emptyView {
    UILabel *label = objc_getAssociatedObject(self, &kEmptyKey);
    if (!label) {
        label = UILabel.new;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = HexColor(0xffffff);
        label.text = BLocalizeKey(@"暂无数据");
        objc_setAssociatedObject(self, &kEmptyKey, label, OBJC_ASSOCIATION_RETAIN);
    }
    return label;
}

@end


@implementation UITableView(Reload)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ExchangeInstanceMethod(self, @selector(reloadData), @selector(__hock_reloadData));
    });
}

- (void)__hock_reloadData {
    [self __hock_reloadData];
    self.isEmpty = self.visibleCells.count==0;
}
@end

@implementation UICollectionView(Reload)
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ExchangeInstanceMethod(self, @selector(reloadData), @selector(__hock_reloadData));
    });
}
- (void)__hock_reloadData {
    [self __hock_reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isEmpty = self.visibleCells.count==0;
    });
}
@end

